package com.ruoyi.common.tenant.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.ruoyi.common.tenant.component.TenantDataSourceManager;
import com.ruoyi.common.tenant.domain.SysTenant;
import com.ruoyi.common.tenant.service.ISysTenantService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 通用配置类
 */

@Configuration
@Slf4j
public class TenantConfiguration {

    @Resource
    private DataSource dataSource;
    @Resource
    private ISysTenantService iSysTenantService;
    @Resource
    private TenantDataSourceManager tenantDataSourceManage;

    @PostConstruct
    public void initTenantDataSource() {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        // 如果没有加载默认master数据源
        if (ObjectUtils.isNotEmpty(ds.getDataSources())
                && !ds.getDataSources().containsKey("master")) {
            List<String> dataSourceKey = new ArrayList<>(ds.getDataSources().keySet());
            // 设置默认的数据源
            log.warn("not set default primary dataSource,now set [{}] default dataSource", dataSourceKey.get(0));
            ds.setPrimary(dataSourceKey.get(0));
        }

        //30s 刷新一次租户数据源，判断是否有变更
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(this::reloadRefreshDataDource
                , 0, 30, TimeUnit.SECONDS);
    }

    @PreDestroy
    public void destory(){
        log.info("TenantConfiguration destory!!");
    }

    public synchronized void reloadRefreshDataDource() {
        try {
            log.info("reloadRefreshDataDource starting.....");
            SysTenant sysTenant = new SysTenant();
            sysTenant.setStatus(0);
            DynamicDataSourceContextHolder.push("tenant");
            List<SysTenant> sysTenants = iSysTenantService.selectSysTenantList(sysTenant);
            tenantDataSourceManage.refreshDataSource(sysTenants);
        }catch (Exception e){
            log.error("reloadRefreshDataDource error,errorMsg:{}",e.getMessage(),e);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
        log.info("reloadRefreshDataDource end.....");
    }

}
